package com.ebuildy.extendedcairngorm.controller
{   
   import com.adobe.cairngorm.commands.ICommand;
   import com.adobe.cairngorm.control.CairngormEvent;
   import com.adobe.cairngorm.control.FrontController;
   import com.ebuildy.extendedcairngorm.service.IServerControllerDelegate;
   import com.ebuildy.extendedcairngorm.service.UrlLoaderDelegate;
   
   import mx.core.ClassFactory;
   import mx.rpc.IResponder;
   import mx.utils.ObjectUtil;
   
	public class ExtendedFrontController extends FrontController
	{				
		/**
		 * Delegate used for the server communication
		 */ 
		[Inspectable(category="General")]
		public var serviceDelegate:ClassFactory;
   	      
      	/**
      	* URL of the Server Controller (if you select the default UrlLoaderDelegate)
      	*/ 
      	[Inspectable(category="General")]
     	public function set urlServerController(value:String):void
     	{
     		if (!serviceDelegate)
     		{
     			serviceDelegate = new ClassFactory(UrlLoaderDelegate);
     			serviceDelegate.properties = {'url':value};
     		}	
     	}
     
     /**
      * Executes the command
      */  
      override protected function executeCommand( event : CairngormEvent ) : void
      {
         var commandToInitialise : Class = getCommand( event.type );
         var commandToExecute:* = new commandToInitialise();

         ICommand(commandToExecute).execute(event);
         
         if (commandToExecute is IServerCommand && !event.isDefaultPrevented())
         {         	
         	var data:Object;
         	var type:String = event.type;
         	
         	if (event.type.indexOf('__execute') == 0)
         	{
         		type = event.data.__type;
         	}
         	
         	trace("--> Execute ServerCommand " + type + ": " + ObjectUtil.toString(event.data));
         	
         	data = new Object();
         	
         	if (ObjectUtil.isSimple(event.data))
         	{
         		data["data"] = event.data;
         	}
         	else
         	{
         		data["data"] = ObjectUtil.copy(event.data);
         	}
         	
         	data["type"] = type;
         	
         	var commandDelegate:IServerControllerDelegate = this.serviceDelegate.newInstance();
         	
         	commandDelegate.call(IResponder(commandToExecute),data);
         } 
      }    
   }   
}
